package com.example.framework.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.client.RestTemplate;

import java.security.interfaces.RSAPublicKey;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)

public class SecurityConfiguration {
	private static final String[] IGNORE_API = new String[]{"/","/home","/home/index"};

	@Bean
	public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http.cors().and().authorizeHttpRequests(
				(authz) -> authz.antMatchers(IGNORE_API).permitAll()
						.anyRequest()
						.authenticated()
				).oauth2ResourceServer()
				.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()));
		return http.build();
	}

	private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter() {
		JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
		jwtConverter.setJwtGrantedAuthoritiesConverter(new RealmRoleConverter());
		return jwtConverter;
	}
	@Autowired
	RestTemplate restTemplate;

	@Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
	String jwkSetUri;

	@Value("${spring.security.oauth2.resourceserver.jwt.key-value}")
	RSAPublicKey jwtKey;

	@Bean
	public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
		//return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(restTemplate).build();
		//myPrivateKeyConverter.convert("");
		//return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
		return NimbusJwtDecoder.withPublicKey(this.jwtKey).build();
	}
	/*
	 * @Bean public GrantedAuthorityDefaults grantedAuthorityDefaults() { return new
	 * GrantedAuthorityDefaults("SCOPE_"); }
	 */
}
